using System;
using System.Collections;
using System.Text;

using log4net;
using log4net.Config;

using MySql.Data.MySqlClient;
using Chat.metier;
using ChatServer;
using NHibernate;

namespace Chat.dao
{
    class ConnectionDAO : IConnectionDAO
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(ConnectionDAO));

        #region IConnectionDAO Membres
        /// <summary>
        /// Retourne un user en fonction de son id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Connection getById(int id)
        {
            ISession session = InitFramework.sessionFactory.OpenSession();
            try
            {
                Connection connection = (Connection)session.Get(typeof(Connection), id);
                session.Close();
                return connection;
            }
            catch (Exception e)
            {
                log.Error("Connection getbyid ", e);
                return null;
            }
        }

        /// <summary>
        /// Retourne toutes les connections
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IList getAll()
        {
            ISession session = InitFramework.sessionFactory.OpenSession();
            try
            {
                IList connections = session.CreateQuery("from Connection").List();
                session.Close();
                return connections;
            }
            catch (Exception e)
            {
                log.Error("Connection getAll", e);
                return null;
            }
        }

        /// <summary>
        /// Sauvegarde un objet en base
        /// </summary>
        /// <param name="conx"></param>
        public void save(Connection conx)
        {
            ISession session = InitFramework.sessionFactory.OpenSession();
            try
            {
                ITransaction tx = session.BeginTransaction();
                session.Save((Object)conx);
                tx.Commit();
                session.Close();
            }
            catch (Exception e)
            {
                log.Error("Connection save", e);
            }
        }

        /// <summary>
        /// Delete un objet en base par son guid
        /// </summary>
        /// <param name="guid"></param>
        public void deleteByGuid(string guid)
        {

            ISession session = InitFramework.sessionFactory.OpenSession();
            try
            {
                ITransaction tx = session.BeginTransaction();
                session.Delete("from Connection where guid='" + guid + "'");
                tx.Commit();
                session.Close();
            }
            catch (Exception e)
            {
                log.Error("Connection deleteId", e);
            }
        }

        #endregion
    }
}
